package com.media.themovieworld.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;

import com.media.themovieworld.R;
import com.media.themovieworld.activity.MovieDetailActivity;
import com.media.themovieworld.api.ApiParams;
import com.media.themovieworld.api.RequestModel;
import com.media.themovieworld.common.adapter.MovieAdapter;
import com.media.themovieworld.common.fragment.MovieTaskScreen;
import com.media.themovieworld.model.AdvertiseModel;
import com.media.themovieworld.model.LoadMoreInfo;
import com.media.themovieworld.model.MovieItemModel;
import com.media.themovieworld.player.FilmPartManage;
import com.media.themovieworld.screen.main.HotMovieScreen;
import com.media.themovieworld.screen.main.NewMovieScreen;
import com.media.themovieworld.screen.main.SuggestMovieScreen;
import com.media.themovieworld.util.AppSettingPrefference;
import com.media.themovieworld.widget.pullandloadmore.LoadMoreListView;
import com.media.themovieworld.widget.pullandloadmore.LoadMoreListView.OnLoadMoreListener;

/**
 * The Class LoadMoreFragment.
 */
public abstract class LoadMoreFragment extends MovieTaskScreen implements OnLoadMoreListener{

	/** The root. */
	protected View root;
	
	/** The content view. */
	protected RelativeLayout contentView;
	
	protected LinearLayout vgNoData;
	
	protected Button btnTryAgain;
	
	/** The m load more list view. */
	protected LoadMoreListView mLoadMoreListView;
	
	/** The m list datas. */
	protected ArrayList<MovieItemModel> mListDatas;
	
	/** The m adapter. */
	protected MovieAdapter mAdapter;
	
	/** The is first load. */
	private boolean isFirstLoad = true;
	
	/** The m load more info. */
	private LoadMoreInfo mLoadMoreInfo;
	
	/* (non-Javadoc)
	 * @see com.media.themovieworld.screen.common.base.BaseFragmentScreen#onCreateContentView(android.view.LayoutInflater, android.view.ViewGroup)
	 */
	@Override
	protected View onCreateContentView(LayoutInflater inflater,
			ViewGroup container) {
		root = inflater.inflate(R.layout.tmw__list_efilm_screen, container,false);
		mLoadMoreListView = (LoadMoreListView) root.findViewById(R.id.tmw__list_efilm_list);
		mLoadMoreInfo = new LoadMoreInfo();
		loadMoreData();
		return root;
	}
	
	/**
	 * Creates the ui.
	 */
	public void createUI(){
		if (getActivity() == null) return;
		mAdapter = new MovieAdapter(getActivity(), mListDatas);
		initAdvertise();
		mLoadMoreListView.setAdapter(mAdapter);
		mLoadMoreListView.setOnLoadMoreListener(this);
		mLoadMoreListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				onListItemClick(position);
			}
			
		});
	}
	
	/**
	 * Load more data.
	 */
	public void loadMoreData(){
//		SoapRequestModel requestData = null;
//		requestData = MovieWorldApi.getFilmRequest(getActivity(), "", getCategoryId(), 0
//				, getMovieType(), mLoadMoreInfo.currentItemVisible, mLoadMoreInfo.currentItemVisible+mLoadMoreInfo.numItemForEachLoad);
		RequestModel requestData = null;
		String language = AppSettingPrefference.getInstance().getMovieLanguage();
		requestData = ApiParams.getFilmParams("", getCategoryId(), 0, getMovieType(), 
				mLoadMoreInfo.currentItemVisible, mLoadMoreInfo.currentItemVisible+mLoadMoreInfo.numItemForEachLoad,language);
		executeSoapTaskReturnList(requestData, isFirstLoad, MovieItemModel.class, new MovieTaskListener() {
			
			@Override
			public void onTaskComplete(Object object) {
				if (object!=null) {
					removeRetryView();
					if (isFirstLoad) {
						isFirstLoad = false;
						mListDatas = (ArrayList<MovieItemModel>) object;
						mLoadMoreInfo.currentItemVisible = mListDatas.size();
						createUI();
					}else{						
						ArrayList<MovieItemModel> movieDatas = (ArrayList<MovieItemModel>) object;
						loadComplete(movieDatas);
					}
				}else{
					if (isFirstLoad) {
						addRetryView();
					}
				}
			}
		});
	}
	
	@Override
	protected void onRetry() {
		removeRetryView();
		resetData();
		loadMoreData();
	}
	
	private void resetData(){
		mLoadMoreInfo.reset();
		isFirstLoad = true;
		mListDatas = new ArrayList<MovieItemModel>();
	}
	
	/**
	 * Load complete.
	 *
	 * @param movieDatas the movie datas
	 */
	private void loadComplete(ArrayList<MovieItemModel> movieDatas){
		if (movieDatas!=null) {
			mListDatas.addAll(movieDatas);
			mAdapter.notifyDataSetChanged();
			mLoadMoreInfo.currentItemVisible += movieDatas.size();
			if (movieDatas.size()<mLoadMoreInfo.numItemForEachLoad) {
				mLoadMoreInfo.isEndOfList = true;
			}
			mLoadMoreListView.onLoadMoreComplete();
		}
	}
	
	/* (non-Javadoc)
	 * @see com.media.themovieworld.widget.pullandloadmore.LoadMoreListView.OnLoadMoreListener#onLoadMore()
	 */
	@Override
	public void onLoadMore() {
		if (!mLoadMoreInfo.isEndOfList) {
			loadMoreData();
		}
	}
	
	protected void onListItemClick(int position){
		MovieItemModel mMovieData = mAdapter.getItem(position-mLoadMoreListView.getHeaderViewsCount());
		FilmPartManage.getInstance().setCurrentFilmData(mMovieData);
		if (mMovieData==null ||mMovieData.filmPartList == null) {
			FilmPartManage.getInstance().setCurrentFilmPart(null);
		}else{
			FilmPartManage.getInstance().setCurrentFilmPart(mMovieData.filmPartList);
		}
		getActivity().startActivity(new Intent(getActivity(), MovieDetailActivity.class));
	}
	
	private void initAdvertise(){
		if(!(this instanceof HotMovieScreen) && !(this instanceof NewMovieScreen) && !(this instanceof SuggestMovieScreen))
			return;
		List<AdvertiseModel> listAdvertise = DataStoreManage.getInstance().getListAdvertise();
		if(listAdvertise == null || listAdvertise.size()==0) return;
		List<AdvertiseModel> topAds = filterAdByPosition(listAdvertise, AdViewProvider.TOP_POSITION);
		List<AdvertiseModel> bottomAds = filterAdByPosition(listAdvertise, AdViewProvider.BOTTOM_POSITION);
		AdvertiseModel topAd = null;
		AdvertiseModel bottomAd = null;
		if(topAds.size()>0){
			topAd = topAds.get(new Random().nextInt(topAds.size()));
		}
		if(bottomAds.size()>0){
			bottomAd = bottomAds.get(new Random().nextInt(bottomAds.size()));
		}
		if(topAd!=null){
			View adHeaderView = AdViewProvider.getInstance().getHeaderAdView(getActivity(), topAd);
			if(adHeaderView!=null){
				ViewGroup vgHeader = getHeaderView();
				vgHeader.removeAllViews();
				vgHeader.addView(adHeaderView);
			}
		}
		if(bottomAd!=null){
			View adFooterView = AdViewProvider.getInstance().getFooterAdView(getActivity(), bottomAd);
			if(adFooterView!=null){
				ViewGroup vgFooter = getFooterView();
				vgFooter.removeAllViews();
				vgFooter.addView(adFooterView);
			}
		}
	}
	
	private ArrayList<AdvertiseModel> filterAdByPosition(List<AdvertiseModel> listAd,int pos){
		ArrayList<AdvertiseModel> ads = new ArrayList<AdvertiseModel>();
		if(listAd.size()>0){
			int adSize = listAd.size();
			for (int i = 0; i < adSize; i++) {
				AdvertiseModel model = listAd.get(i);
				if(model.position == pos){
					ads.add(model);
				}
			}
		}
		return ads;
	}
	
	/**
	 * Gets the category id.
	 *
	 * @return the category id
	 */
	protected abstract String getCategoryId();
	
	protected int getMovieType(){
		return 0;
	}
	/**
	 * Checks if is list with header.
	 *
	 * @return true, if is list with header
	 */
	protected boolean isListWithHeader(){
		return false;
	}
	
}
